package org.crc.myvhrb.service;

import org.crc.myvhrb.mapper.HrMapper;
import org.crc.myvhrb.mapper.HrRoleMapper;
import org.crc.myvhrb.model.Hr;
import org.crc.myvhrb.utils.HrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * CRC
 * 2021/8/1
 */
@Service
public class HrService implements UserDetailsService {

    @Autowired
    HrMapper hrMapper;

    @Autowired
    HrRoleMapper hrRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        // 根据用户名查询用户信息，这里就不做逻辑判断了
        Hr hr = hrMapper.getUserByUsername(name);
        if (hr==null){
            throw new UsernameNotFoundException("用户名不存在！");
        }

        hr.setRoles(hrMapper.getHrRolesById(hr.getId()));
        return hr;
    }

    // 查询所有 hr 数据
    public List<Hr> getAllHrs(String keywords) {
        return hrMapper.getAllHrs(HrUtils.getCurrentHr().getId(),keywords);
    }

    public int updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    @Transactional
    public boolean updateHrRole(Integer hrid, Integer[] rids) {
        // 删除用户角色
        hrRoleMapper.deleteByHrId(hrid);
        if (rids.length == 0 || rids == null){
            return true;
        }
        // 添加用户角色
        return hrRoleMapper.addRole(hrid,rids) == rids.length;
    }

    public int deleteHr(Integer id) {
        return hrMapper.deleteByPrimaryKey(id);
    }

    public List<Hr> getAllHrsExceptCurrentHr() {
        return hrMapper.getAllHrsExceptCurrentHr(HrUtils.getCurrentHr().getId());
    }
}
